//
//  YLWKWebViewVC.m
//  yuLink
//
//  Created by aiwoba on 2021/4/12.
//

#import "YLWKWebViewVC.h"
#import <WebKit/WebKit.h>
#import "YLWKWebViewModel.h"
#import "NetworkManager.h"

@interface YLWKWebViewVC ()<WKNavigationDelegate>
//@property (nonatomic, strong) UIView *navigationView;
//@property (nonatomic, strong) YLStoreNavigationView *navigationView;

@property (nonatomic, strong) WKWebView *contentWebView;
@property (nonatomic, strong) UIProgressView *progressView;
@property (nonatomic, strong) NSDate *performance_startTime;//加载开始时间
@property (nonatomic , assign)NSInteger timeInterval; ///时间间隔 s
@property (nonatomic, strong) dispatch_source_t timer;


@end

@implementation YLWKWebViewVC

- (void)viewDidLoad {
   [super viewDidLoad];
   [self createSubViews];
   [self layoutSubviewsMy];

        [self askDataSouce];
    
   
 }
- (void)viewWillAppear:(BOOL)animated{
   [super viewWillAppear:animated];
//   [self.navigationController setNavigationBarHidden:YES];
//[self.navigationController setNavigationBarHidden:NO animated:YES];

   
}
- (void)viewWillDisappear:(BOOL)animated{
   [super viewWillDisappear:animated];
//   [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)askDataSouce {
    self.title = self.titleText ? : @"";
    
    self.navigationView.title = self.titleText ? : @"";
    
    if ([NetworkManager isReachable]) {
 
        NSMutableURLRequest *request = nil;
         request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:self.urlString] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
        [self.contentWebView loadRequest:request];
    } else {
        [self showLoadErrorView];
    }
}
-(void)createSubViews{
   self.view.backgroundColor = COLOR_BG;
   [self.view addSubview:self.contentWebView];
    
//    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:readImageFromImageName(@"icon_outline_back21") style:UIBarButtonItemStyleDone target:self action:@selector(back)];
    

}
-(void)layoutSubviewsMy{
//   [self.navigationView mas_makeConstraints:^(MASConstraintMaker *make) {
//       make.left.right.top. mas_equalTo(self.view);
//       make.height.mas_equalTo(NavigationHeight);
//   }];
    [self.contentWebView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(NavigationHeight);
        make.left.and.right.mas_equalTo(self.view);
        make.bottom.mas_equalTo(self.view.mas_bottom).offset(-HomeBarH);
    }];
   
}


- (void)viewDidLayoutSubviews {
    self.progressView.frame = CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, 0.5);
}
- (void)showLoadErrorView {
   
    [BaseToastView showToastWithText:REAPPString(@"error") Type:YLToastTypeShort ToView:self.view];
}
#pragma mark Actionn
-(void)storeNavigationView:(YLStoreNavigationView *)navigationView didClickBackBtn:(UIButton *)button{
    if ([self.contentWebView canGoBack]) {

        [self.contentWebView goBack];
        return;
    }

   [self.navigationController popViewControllerAnimated:YES];
}

- (void)back{
    if ([self.contentWebView canGoBack]) {

        [self.contentWebView goBack];
        return;
    }
    if (_isPop) {
        [self.navigationController popToRootViewControllerAnimated:YES];

    } else {
        [self.navigationController popViewControllerAnimated:YES];

    }
    
}

-(void)startRefreshingWeb{
    _contentWebView.scrollView.scrollEnabled = YES;
    @weakify(self);
     [_contentWebView.scrollView.mj_header beginRefreshingWithCompletionBlock:^{
            @strongify(self);
        [self.contentWebView evaluateJavaScript:@"window.location.reload()" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
            [self endRefreshingWeb];
        }];
    } ];
}

- (void)endRefreshingWeb{
    [_contentWebView.scrollView.mj_header endRefreshing];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([self.progressView isDescendantOfView:self.contentWebView]) {
        if ([keyPath isEqualToString:@"estimatedProgress"]) {
            self.progressView.progress = self.contentWebView.estimatedProgress;
            if (self.progressView.progress == 1) {
                /*
                 *添加一个简单的动画，将progressView的Height变为1.4倍，在开始加载网页的代理中会恢复为1.5倍
                 *动画时长0.25s，延时0.3s后开始动画
                 *动画结束后将progressView隐藏
                 */
                @weakify(self);
                [UIView animateWithDuration:0.25f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
                    @strongify(self);
                    self.progressView.transform = CGAffineTransformMakeScale(1.0f, 0.8f);
                } completion:^(BOOL finished) {
                    @strongify(self);
                    self.progressView.hidden = YES;
                    
                }];
            }
        }else{
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    }
}

#pragma mark - system delegate
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    NSLog(@"message.name===%@", message.name);
}

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    if ([self.progressView isDescendantOfView:self.contentWebView]) {
        self.progressView.hidden = NO;
        self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.0f);
    }
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
      NSString *lastTitle = self.contentWebView.backForwardList.backItem.title;
//         [_navigationView updateTitleText:webView.title];
     [self endRefreshingWeb];
}

- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
//     [_navigationView updateTitleText:webView.title];
    [self endRefreshingWeb];
}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
//     [_navigationView updateTitleText:webView.title];
    [self endRefreshingWeb];
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    decisionHandler(WKNavigationActionPolicyAllow);
}


- (WKWebView *)contentWebView {
    @weakify(self);
    if (!_contentWebView) {
        WKUserContentController *userContentController = [[WKUserContentController alloc] init];
        WKUserScript *userScript = [[WKUserScript alloc] initWithSource:[NSString stringWithFormat:@"%@",[YLWKWebViewModel defaultCookieConfiguration] ] injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
        [userContentController addUserScript:userScript];
        
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        config.selectionGranularity = WKSelectionGranularityCharacter;
        config.userContentController = userContentController;
        config.mediaPlaybackRequiresUserAction = false;
        config.allowsInlineMediaPlayback = YES;
        
        _contentWebView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:config];
        
        _contentWebView.navigationDelegate = self;
        //添加监测网页加载进度的观察者
        [_contentWebView addObserver:self
                          forKeyPath:@"estimatedProgress"
                             options:0
                             context:nil];
        self.progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, 0.5)];
        self.progressView.progressTintColor = COLOR_BG;
        self.progressView.trackTintColor = COLOR_BG;
        [_contentWebView addSubview:self.progressView];
        @strongify(self);
        [self startRefreshingWeb];
    }
    
    return _contentWebView;
}

- (void)dealloc {
    NSLog(@"销毁次级webView界面");
//    [self timeoutAction];
    _contentWebView.scrollView.delegate = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [_contentWebView removeObserver:self forKeyPath:@"estimatedProgress"];
}





@end
